package cn.anzhiyublog.staranimegallery.model.enums;

import cn.anzhiyublog.staranimegallery.model.domain.User;
import lombok.Getter;

/**
 * 权限组枚举
 *
 * @author 安知一只鱼
 */
@Getter
public enum Authority {
    /**
     * General用户角色 Manage管理角色
     */
    GENERAL(0,"general", new int[]{0, 9}),
    MANAGE(1,"manage", new int[]{10, 19});

    private final int code;
    private final String authority;
    private final int[] range;

    Authority(int code, String authority, int[] range) {
        this.code = code;
        this.authority = authority;
        this.range = range;
    }

    /**
     * 根据code获取枚举
     */
    public static Authority getEnumByCode(int code) {
        for (Authority authority : values()) {
            if (authority.getCode() == code) {
                return authority;
            }
        }
        return null;
    }

    /**
     * 根据角色获取枚举
     */
    private static Authority getEnumByRole(Role role){
        for (Authority authority : values()) {
            if (authority.getRange()[0] <= role.getCode() && authority.getRange()[1] >= role.getCode()) {
                return authority;
            }
        }
        return null;
    }

    /**
     * 判断是否为管理员
     */
    public static boolean inManage(Role role){
        Authority authority = getEnumByRole(role);
        return authority != null && authority.getCode() == MANAGE.getCode();
    }
    public static boolean inManage(User user){
        return inManage(Role.getEnumByCode(user.getRole()));
    }


    /**
     * 判断是否为普通用户
     */
    public static boolean inGeneral(Role role){
        Authority authority = getEnumByRole(role);
        return authority != null && authority.getCode() == GENERAL.getCode();
    }
}
